package com.web709.controller;

import com.web709.common.R;
import com.web709.entity.Activity;
import com.web709.service.ActivityParticipantService;
import com.web709.service.ActivityService;
import com.web709.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activities")
@Api(tags = "活动管理接口", value = "活动创建、查询及管理")
@Slf4j
public class ActivitiesController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityParticipantService activityParticipantService;

    @PostMapping("/publish")
    @ApiOperation(value = "发布新活动",
                notes = "管理员创建新的活动信息，包含标题、描述、时间等基本信息，参数格式：{\n" +
                        "  \"adminId\": 1,\n" +
                        "  \"description\": \"周游世界\",\n" +
                        "  \"endTime\": \"2024-12-24 12:22:22\",\n" +
                        "  \"imgPath\": \"1.jpg\",\n" +
                        "  \"startTime\": \"2024-12-24 12:22:22\",\n" +
                        "  \"title\": \"你好世界\"\n" +
                        "}")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "activity",
                        value = "活动实体对象",
                        required = true,
                        dataTypeClass = Activity.class,
                        paramType = "body"), // 请求体中的活动对象
            @ApiImplicitParam(name = "token",
                        value = "管理员token",
                        required = true,
                        paramType = "header",
                        dataType = "String")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "活动创建成功"),
        @ApiResponse(code = 400, message = "参数校验失败"),
        @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public R<String> publish(@RequestBody Activity activity) {
        activityService.save(activity);
        return R.success("发布成功");
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取活动列表",
                notes = "分页查询所有有效活动信息，默认按创建时间倒序排列")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page",
                        value = "页码（从1开始）",
                        defaultValue = "1",
                        dataType = "Integer",
                        paramType = "query"),
        @ApiImplicitParam(name = "size",
                        value = "每页数量",
                        defaultValue = "10",
                        dataType = "Integer",
                        paramType = "query")
    })
    public R<List<Activity>> listActivities(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        List<Activity> activities = activityService.listByPage(page, size);
        return R.success(activities);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "获取活动详情",
                notes = "根据活动ID获取完整活动信息及参与情况")
    @ApiImplicitParam(name = "id",
                    value = "活动ID",
                    required = true,
                    dataType = "Integer",
                    paramType = "path")
    public R<Activity> getActivityDetail(@PathVariable Integer id) {
        Activity activity = activityService.getByIdWithParticipants(id);
        return R.success(activity);
    }


    //传入活动ID、用户ID，为活动添加参与人员
    @GetMapping("/ujoin/{id}")
    @ApiOperation(value = "参与活动，这个接口是给用户参加活动用的",
                notes = "根据活动ID，将用户添加到活动参与人员列表中")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id",
                        value = "活动ID",
                        required = true,
                        dataType = "Integer",
                        paramType = "path"),
            @ApiImplicitParam(name = "token",
                        value = "用户token",
                        required = true,
                        paramType = "header",
                        dataType = "String")
    })
    public R<String> joinActivity(@PathVariable Integer id, HttpServletRequest request)  {
        try {
            String token = request.getHeader("token");
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("userId");
            activityParticipantService.save(id, userId);
            return R.success("参与成功");
        } catch (RuntimeException e) {
            return R.success("您已经参加过该活动");
        }
    }

    @GetMapping("/vjoin/{id}")
    @ApiOperation(value = "参与活动，这个接口是给志愿者参加活动用的",
            notes = "根据活动ID，将志愿者添加到活动参与人员列表中")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",
                    value = "活动ID",
                    required = true,
                    dataType = "Integer",
                    paramType = "path"),
            @ApiImplicitParam(name = "token",
                    value = "志愿者token",
                    required = true,
                    paramType = "header",
                    dataType = "String")
    })
    public R<String> joinActivityV(@PathVariable Integer id, HttpServletRequest request)  {
        try {
            String token = request.getHeader("token");
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("userId");
            activityParticipantService.saveV(id, userId);
            return R.success("参与成功");
        } catch (RuntimeException e) {
            return R.success("您已经参加过该活动");
        }
    }


    //传入用户的ID，返回用户参加的活动列表
    @GetMapping("/list/activitysu/count/")
    @ApiOperation(value = "获取用户参加的活动列表",
                notes = "根据用户ID，获取用户参加的活动列表,直接带上token就可以了")
    @ApiImplicitParam(name = "token", required = false,paramType = "header",dataType = "String")
    public R<List<Activity>> listUserActivities(HttpServletRequest request)  {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("userId");
        List<Activity> activities = activityService.listByUserId(userId);
        return R.success(activities);
    }


    //传入用户的ID，返回用户参加的活动列表
    @GetMapping("/list/activitysv/count/")
    @ApiOperation(value = "获取志愿者参加的活动列表",
            notes = "根据用户ID，获取用户参加的活动列表,直接带上token就可以了")
    @ApiImplicitParam(name = "token", required = false,paramType = "header",dataType = "String")
    public R<List<Activity>> listUserActivitiesV(HttpServletRequest request)  {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("userId");
        List<Activity> activities = activityService.listByUserIdV(userId);
        return R.success(activities);
    }

    //修改活动信息
    @PutMapping("/update")
    @ApiOperation(value = "更新活动信息", notes = "更新活动信息，参数格式：{\n" +
            "  \"id\": 1,\n" +
            "  \"description\": \"周游世界\",\n" +
            "  \"endTime\": \"2024-12-24 12:22:22\",\n" +
            "  \"imgPath\": \"1.jpg\",\n" +
            "  \"startTime\": \"2024-12-24 12:22:22\",\n" +
            "  \"title\": \"你好世界\"\n" +
            "}")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "activity", value = "活动信息", required = true, dataType = "Activity"),
    })
    public R<String> update(@RequestBody Activity activity) {
        activity.setDescription(activity.getDescription());
        activityService.updateById(activity);
        return R.success("更新成功");
    }

    //删除
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除活动", notes = "根据活动ID删除活动,当活动删除时，同时删除参与人员！！！管理员用的")
    @ApiImplicitParam(name = "id", value = "活动ID", required = true, dataType = "Integer")
    public R<String> delete(@PathVariable Integer id) {
        int activityId = activityService.getById(id).getId();
        activityService.removeById(id);
        activityParticipantService.removeByActivityId(activityId);
        return R.success("删除成功");
    }

    /**
     * 活动参与度分析接口
     * 获取各活动参与人数统计，包括用户和志愿者的分布
     */
    @GetMapping("/analytics/participation")
    @ApiOperation(value = "活动参与度分析", 
                notes = "统计各活动的参与人数(用户/志愿者)分布")
    @ApiImplicitParam(name = "token", required = false, paramType = "header", dataType = "String")
    public R<Map<String, Object>> getParticipationAnalytics() {
        try {
            log.info("正在获取活动参与度分析数据");
            
            // 获取活动参与统计数据
            List<Map<String, Object>> participationStats = activityParticipantService.getParticipationStatistics();
            
            Map<String, Object> result = new HashMap<>();
            result.put("participationStats", participationStats);
            
            log.info("成功获取活动参与度分析数据，共{}条记录", participationStats.size());
            return R.success(result);
        } catch (Exception e) {
            log.error("获取活动参与度分析数据失败", e);
            return R.error("获取数据失败：" + e.getMessage());
        }
    }

}



